﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DAL;
using CommontLibrary;
public partial class UserControl_Role_insertQuyen : System.Web.UI.UserControl
{

#region "Member variables"
    private int intUserID = 0;
    private int intModuleID = 0;
    bool boolRead = false;
    bool boolWrite = false;
    bool boolUpdate = false;
    bool boolDelete = false;
    DAQuyen objQuyen;
    DANguoidung objNguoidung;
    DALog objLog;
#endregion
#region "Parametter variables"
    // Ham lay Bind du lieu
    public SqlConnection ConnectionView
    {
        get
        {
            object obj2 = this.ViewState["ConnectionView"];
            if (obj2 != null)
            {
                return (SqlConnection)obj2;
            }
            return null;
        }
        set
        {
            this.ViewState["ConnectionView"] = value;
        }
    }
#endregion
#region "Private methods"
    // Hien thi Quyen tren datagrid
    private void loadQuyen()
    {
        DataSet dsQuyen = objQuyen.loadQuyenGridView();
        if (dsQuyen != null && dsQuyen.Tables[0].Rows.Count > 0)
        {
            int i = 1;
            DataTable dt = dsQuyen.Tables[0].Clone();
            DataRow[] drs = dsQuyen.Tables[0].Select("NhomID = 0");
            foreach (DataRow dr in drs)
            {
                dr["Seq"] = i.ToString();
                i++;
                dt.ImportRow(dr);
                loadQuyenub(dt, dr["ID"].ToString(), dsQuyen.Tables[0], "--", ref i);

            }
            BindData.bindGridView(this.ddlQuyen, dt);
        }
    }
    private void loadQuyenub(DataTable dtTemp, string strCheck, DataTable dt, string strPath, ref int i)
    {
        DataRow[] drs = dt.Select("NhomID =" + strCheck);
        foreach (DataRow dr in drs)
        {
            dr["ParentName"] = strPath + dr["ParentName"].ToString();
            dr["Seq"] = i.ToString();
            i++;
            dtTemp.ImportRow(dr);
            loadQuyenub(dtTemp, dr["ID"].ToString(), dt, strPath + "--", ref i);
        }
    }//Load Libary Insert
    private void loadNhomID(DropDownList ddlTemp)
    {
        DataSet dsQuyen = objQuyen.loadQuyen();
        if (dsQuyen != null && dsQuyen.Tables[0].Rows.Count > 0)
        {
            DataRow[] drs = dsQuyen.Tables[0].Select("NhomID = 0");
            ddlTemp.Items.Clear();
            foreach (DataRow dr in drs)
            {
                ListItem liTemp = new ListItem();
                liTemp.Text = dr["Tennhom"].ToString();
                liTemp.Value = dr["ID"].ToString();
                ddlTemp.Items.Add(liTemp);
                loadNhomIDSub(ddlTemp, dr["ID"].ToString(), dsQuyen.Tables[0], "--");
            }
            this.cbNhomID.Visible = true;
            ddlTemp.Visible = true;
            this.lblNhomID.Visible = true;
        }
        else
        {
            this.cbNhomID.Visible = false;
            ddlTemp.Visible = false;
            this.lblNhomID.Visible = false;
        }
    }
    private void loadNhomIDSub(DropDownList ddlTemp, string strCheck, DataTable dt, string strPath)
    {
        DataRow[] drs = dt.Select("NhomID =" + strCheck);
        foreach (DataRow dr in drs)
        {
            ListItem liTemp = new ListItem();
            liTemp.Text = strPath + dr["Tennhom"].ToString();
            liTemp.Value = dr["ID"].ToString();
            ddlTemp.Items.Add(liTemp);
            loadNhomIDSub(ddlTemp, dr["ID"].ToString(), dt, strPath + "--");
        }
    }
    //Load Libary Update
    private void loadQuyenView(DropDownList ddlTemp, int intCheck)
    {
        DataSet dsQuyen = objQuyen.loadQuyen();
        if (dsQuyen != null && dsQuyen.Tables[0].Rows.Count > 0)
        {
            DataRow[] drs = dsQuyen.Tables[0].Select("NhomID = 0");
            ddlTemp.Items.Clear();
            foreach (DataRow dr in drs)
            {
                ListItem liTemp = new ListItem();
                liTemp.Text = dr["Tennhom"].ToString();
                liTemp.Value = dr["ID"].ToString();
                if (intCheck.ToString() != dr["ID"].ToString())
                {
                    ddlTemp.Items.Add(liTemp);
                    loadQuyenViewSub(ddlTemp, dr["ID"].ToString(), dsQuyen.Tables[0], "--", intCheck);
                }
            }
        }
    }
    private void loadQuyenViewSub(DropDownList ddlTemp, string strCheck, DataTable dt, string strPath, int intCheck)
    {
        DataRow[] drs = dt.Select("NhomID =" + strCheck);
        foreach (DataRow dr in drs)
        {
            ListItem liTemp = new ListItem();
            liTemp.Text = strPath + dr["Tennhom"].ToString();
            liTemp.Value = dr["ID"].ToString();
            if (intCheck.ToString() != dr["ID"].ToString())
            {
                ddlTemp.Items.Add(liTemp);
                loadQuyenViewSub(ddlTemp, dr["ID"].ToString(), dt, strPath + "--", intCheck);
            }
        }
    }
    // Lay tat ca cac du lieu cua bang Role theo ngon ngu cho vao DropDownList trong DataGrid
    private void loadNhomIDGV(int intIndexDatagrid)
    {
        loadQuyen();
        Label lblIDTemp = (Label)ddlQuyen.Rows[intIndexDatagrid].Cells[3].FindControl("lblID");
        DropDownList ddlTemp = (DropDownList)ddlQuyen.Rows[intIndexDatagrid].Cells[3].FindControl("ddlNhomIDGV");
        Label lblTemp = (Label)ddlQuyen.Rows[intIndexDatagrid].Cells[3].FindControl("lblNhomIDGV");
        CheckBox cbTemp = (CheckBox)ddlQuyen.Rows[intIndexDatagrid].Cells[3].FindControl("cbNhomIDGV");
        lblTemp.Visible = false;
        int myintUser = Convert.ToInt32(lblTemp.Text);
        cbTemp.Checked = false;
        if (myintUser > 0)
        {
            loadQuyenView(ddlTemp, Convert.ToInt32(lblIDTemp.Text));
            BindData.selectDropDowList(ddlTemp, myintUser.ToString());
            if (ddlTemp.Items.Count == 0)
            {
                cbTemp.Checked = true;
                ddlTemp.Enabled = false;
            }
        }
        else
        {
            loadQuyenView(ddlTemp, Convert.ToInt32(lblIDTemp.Text));
            ddlTemp.Enabled = false;
            cbTemp.Checked = true;
        }
    }
    //check validation
    private bool checkValidation()
    {
        if (this.txtTennhom.Text.Trim().Equals(""))
        {
            this.ctvTennhom.IsValid = false;
            return false;
        }
        else
        {
            return true;
        }
    }
    //Reset text cua from    
    private void resetFrom()
    {
        this.txtTennhom.Text = "";
    }
    // Tao Thu vien moi
    private void CreateQuyen()
    {
        if (Page.IsValid)
        {
            if (checkValidation())
            {
                string strTennhom = this.txtTennhom.Text.Trim();
                int intNhomID = 0;
                if (cbNhomID.Checked == false)
                {
                    if (!(this.ddlNhomID.Items.Count == 0))
                    {
                        intNhomID = Convert.ToInt32(this.ddlNhomID.SelectedValue);
                    }
                }

                int intChẹck = objQuyen.insertQuyen(strTennhom, intNhomID);
                if (intChẹck > 0)
                {
                    this.lblMess.Text = "Thêm bản ghi thành công";
                    Session["UserID"] = intUserID;
                    objLog.insertLog(0, 0, 13, intUserID);
                    resetFrom();
                    loadQuyen();
                    loadNhomID(this.ddlNhomID);
                }
                else if (intChẹck == 0)
                {
                    this.lblMess.Text = "Bản ghi này đã có trong dữ liệu!";
                }
                else
                {
                    this.lblMess.Text = "Lỗi trong quá trình thêm mới bản ghi!";
                }
            }
        }
    }
    // Sua Thu vien 
    private void UpdateQuyen(object source, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        int intID = Convert.ToInt32(ddlQuyen.DataKeys[e.RowIndex].Value);
        string strTennhom = "";
        int intNhomID = 0;
        foreach (Control ctrl in ddlQuyen.Rows[e.RowIndex].Cells[3].Controls)
        {
            if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
            {
                strTennhom = ((TextBox)ctrl).Text;
                break;
            }
        }
        this.ctvTennhom.IsValid = true;
        if (strTennhom.Equals(""))
        {
            this.ctvTennhom.ErrorMessage = "Bạn phải nhập tên ";
            this.ctvTennhom.IsValid = false;
        }
        else
        {
            try
            {

                foreach (Control ctrl in ddlQuyen.Rows[e.RowIndex].Cells[2].Controls)
                {
                    if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                    {
                        intNhomID = Convert.ToInt32(((DropDownList)ctrl).SelectedValue);
                        break;
                    }
                }
            }
            catch
            {
                intNhomID = 0;
            }
            int intChẹck = objQuyen.updateQuyen(intID, strTennhom, intNhomID);
            if (intChẹck > 0)
            {
                this.lblMess.Text = "Sửa thành công bản ghi";
                Session["UserID"] = intUserID;
                objLog.insertLog(0, 0, 12, intUserID);
                ddlQuyen.EditIndex = -1;
                loadQuyen();
                loadNhomID(this.ddlNhomID);
            }
            else if (intChẹck == 0)
            {
                this.lblMess.Text = "Bản ghi này đã có trong dữ liệu!";
            }
            else
            {
                this.lblMess.Text = "Lỗi trong quá trình sửa bản ghi!";
            }
        }
    }
    // Xoa file
    private void DeleteQuyen(object source, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int intID = Convert.ToInt32(ddlQuyen.DataKeys[e.RowIndex].Value);
        int intChẹck = objQuyen.removeQuyen(intID);
        if (intChẹck > 0)
        {
            this.lblMess.Text = "Xóa thành công bản ghi";
            Session["UserID"] = intUserID;
            objLog.insertLog(0, 0, 11, intUserID);
            loadQuyen();
            loadNhomID(this.ddlNhomID);
        }
        else
        {
            this.lblMess.Text = "Lỗi trong quá trình xóa bản ghi!";
        }
    }
#endregion
#region "Events handle"
    // Check quyen han su dung
    private void CheckUserModule(int UserID, int ModuleID)
    {
        //objUser.CheckUserModule(UserID, ModuleID, ref boolRead, ref boolWrite
        //    , ref boolUpdate, ref boolDelete);
        //if (!boolRead)
        //{
        //    this.btnInsert.Visible = false;
        //    this.ddlQuyen.Visible = false;
        //}
        //if (!boolWrite)
        //{
        //    this.btnInsert.Visible = false;
        //}
        //if (!boolUpdate)
        //{
        //    this.ddlQuyen.Columns[5].Visible = false;
        //    this.ddlQuyen.Columns[7].Visible = false;
        //}
        //if (!boolDelete)
        //{
        //    this.ddlQuyen.Columns[6].Visible = false;
        //    this.ddlQuyen.Visible = false;
        //    this.ddlQuyen.Visible = true;
        //}
        //else
        //{
        //    this.ddlQuyen.Visible = true;
        //}
    }
    private void loadDataAccess()
    {
        SqlConnection sqlConnec = ConnectData.getConnection();
        objQuyen = new DAQuyen(sqlConnec);
        objNguoidung = new DANguoidung(sqlConnec);
        objLog = new DALog(sqlConnec);
    }
// Main load
    protected void Page_Load(object sender, EventArgs e)
    {
        intUserID = Convert.ToInt32(Session["UserID"].ToString().Trim());
        intModuleID = Convert.ToInt32(Request.QueryString["ChucNang"].Trim());
        loadDataAccess();
        if (!Page.IsPostBack)
        {
            CheckUserModule(intUserID, intModuleID);
            loadQuyen();
            loadNhomID(this.ddlNhomID);
            if (this.ddlNhomID.Items.Count == 0)
            {
                this.ddlNhomID.Enabled = false;
                this.cbNhomID.Checked = true;
            }
        }
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        ddlQuyen.EditIndex = -1;
        this.lblMess.Text = "";
        CreateQuyen();
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ddlQuyen.EditIndex = -1;
        this.lblMess.Text = "";
        resetFrom();
    }
    protected void ddlQuyen_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.lblMess.Text = "";
        ddlQuyen.EditIndex = -1;
        loadQuyen();
    }
    protected void ddlQuyen_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
                e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";// Modify
                ImageButton lbtDeleteTemp = ((ImageButton)e.Row.FindControl("lbtDelete"));
                if (lbtDeleteTemp != null)
                {
                    string strDelete = "Bạn chắc chắn muốn xóa OK , Bạn hủy lệnh CANCEL ";
                    lbtDeleteTemp.Attributes.Add("Onclick", "javascript:if(confirm('" + strDelete + "')) {return true} else {return false};");
                }
                Label lblNhomIDGVCheckTemp = ((Label)e.Row.FindControl("lblNhomIDGVCheck"));
                if (lblNhomIDGVCheckTemp != null)
                {
                    int intID = Convert.ToInt32(lblNhomIDGVCheckTemp.Text);
                    lblNhomIDGVCheckTemp.Text = "Không có";
                    if (intID > 0)
                    {
                        DataRow dr = objQuyen.loadID(intID);
                        if (dr != null)
                        {
                            lblNhomIDGVCheckTemp.Text = lblNhomIDGVCheckTemp.ToolTip + dr["Tennhom"].ToString();
                            lblNhomIDGVCheckTemp.ToolTip = "";
                        }
                    }

                }
            }
        }
    }
    protected void ddlQuyen_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ddlQuyen.EditIndex = -1;
        this.lblMess.Text = "";
        DeleteQuyen(sender, e);
    }
    protected void ddlQuyen_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.lblMess.Text = "";
        ddlQuyen.EditIndex = e.NewEditIndex;
        loadNhomIDGV(e.NewEditIndex);
    }
    protected void ddlQuyen_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        this.lblMess.Text = "";
        UpdateQuyen(sender, e);
    }
    //Su kien thay doi cap cha tao moi hay ko
    protected void cbNhomIDGV_CheckedChanged(object sender, EventArgs e)
    {
        this.lblMess.Text = "";
        CheckBox cbTemp = ((CheckBox)sender);
        if (!cbTemp.ToolTip.Equals(""))
        {
            int i = Convert.ToInt32(cbTemp.ToolTip);
            DropDownList ddlNhomIDTemp = (DropDownList)(ddlQuyen.Rows[i].FindControl("ddlNhomIDGV"));
            if (ddlNhomIDTemp.Items.Count > 0)
            {
                if (cbTemp.Checked)
                {
                    ddlNhomIDTemp.Enabled = false;
                    cbTemp.Checked = true;
                    cbTemp.Text = "Không có nhóm cha";
                }
                else
                {
                    ddlNhomIDTemp.Enabled = true;
                    cbTemp.Checked = false;
                    cbTemp.Text = "Có nhóm cha";
                }
            }
            else
            {
                ddlNhomIDTemp.Enabled = false;
                cbTemp.Checked = true;
                cbTemp.Text = "Không có nhóm cha";
            }
        }

    }

    //Su kien thay doi cap cha tao moi hay ko
    protected void cbNhomID_CheckedChanged(object sender, EventArgs e)
    {
        ddlQuyen.EditIndex = -1;
        this.lblMess.Text = "";
        if (ddlNhomID.Items.Count > 0)
        {
            if (this.cbNhomID.Checked)
            {
                this.ddlNhomID.Enabled = false;
                this.cbNhomID.Checked = true;
                this.cbNhomID.Text = "Không có nhóm cha";
            }
            else
            {
                this.ddlNhomID.Enabled = true;
                this.cbNhomID.Checked = false;
                this.cbNhomID.Text = "Có nhóm cha";
            }
        }
        else
        {
            this.ddlNhomID.Enabled = false;
            this.cbNhomID.Checked = true;
            this.cbNhomID.Text = "Không có nhóm cha";
        }
    }
    protected void ddlQuyen_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.ddlQuyen.EditIndex = -1;
        this.ddlQuyen.PageIndex = e.NewPageIndex;
    }
#endregion
   
}
